<script setup lang="ts">
import { ref, reactive, onMounted, computed, shallowRef, onUnmounted, watch } from 'vue';
import { traduction } from '@/utils/language';
import { IPowerOnPolicy, IVirtualKeyInfo } from '@/model/System/power-interface';
import Dialog from '@/components/Dialog/Dialog.vue';
import HelpIcon from '@/components/HelpIcon/HelpIcon.vue';
import Editor from '@/components/Editor/Editor.vue';
import { getPowerControl, setPowerControl, setPowerOnOff } from '../../services/power.services';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import useStore from '@/stores';
import { compareObjectEqual, showElMessage } from '@/utils/utils';
import { loading, getStoreData, setStoreData } from '@/utils/composition';
import SingleLineFailurePrompt from '@/components/SingleLineFailurePrompt/SingleLineFailurePrompt.vue';
import { deepClone } from '@/utils/utils';
import { systemId } from '../../../Info/product.datatype';
import { IconAlarm, IconError, IconSuccess } from '@computing/opendesign-icons';
import { showFWMessage } from '@/pages/System/Power/utils/common';

const store = useStore();
// 系统锁定状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const isArm = getStoreData('loct', 'armspt');
const multihost = getStoreData('loct', 'multihost');
const isPrivileges = checkPrivil(UserPrivil.powerControl);

const saveBtn = ref(true);

const safePowerOffTimoutSeconds = ref(0);
const switchState = ref(true);
const powerOnPolicySelected = ref(traduction('POWER_KEEP_ON'));
const powerOnDelayedSelected = ref('');
const leakageSupport = ref(false);
const targetData = reactive({
  powerState: '',
});
// 系统状态
const systemState = ref('POWER_OFF');
const powerType = ref('');

const multipleSelection = ref<any[]>([]);

const oldData: any = {};
let oldSeconds: any = '';

let getStateTimer: any = null;
const multipleTable = ref();

// 虚拟按键列表
const virtualKeyLists: Array<IVirtualKeyInfo> = reactive([
  {
    id: 'on',
    show: true,
    information: 'POWER_ON',
    className: 'power-on',
  },
  {
    id: 'off',
    show: true,
    information: 'POWER_OFF',
    className: 'power-off',
  },
  {
    id: 'forcedOff',
    show: true,
    information: 'POWER_STRONG_DOWN',
    promptMessage: 'POWER_STRONG_DOWN_TIP',
    promptId: 'forcePowerOff',
    helpTips: 'POWER_FORCED_OFF_TIP',
  },
  {
    id: 'forcedRestart',
    show: true,
    information: 'POWER_FORCED_RESTART',
    promptMessage: 'POWER_STRONG_REST_TIP',
    promptId: 'forcePowerRestart',
    helpTips: 'POWER_FORCED_RESTART_TIP',
  },
  {
    id: 'powerCycle',
    show: true,
    information: 'POWER_SAFE_RESTART',
    promptMessage: 'POWER_SAFE_RESTART_TIP',
    promptId: 'safePowerToggle',
    helpTips: 'POWER_SAFE_CYCLE_TIP',
  },
  {
    id: 'forcedCycle',
    show: true,
    information: 'HEADER_POWER_FORECE_OFF_ON',
    promptMessage: 'POWER_STRONG_OFF_ON_TIP',
    promptId: 'forcePowerToggle',
    helpTips: 'POWER_FORCED_CYCLE_TIP',
  },
]);

const tableData = reactive<any>([
  
]);

function powerOffTimeChange(val: boolean, item: any) {
  loading(true);
  const params = {
    PowerOffAfterTimeout: {
      Enabled: val ? 'On' : 'Off',
    },
    SystemId: item.id,
  };

  setPowerControl(params)
    .then(res => {
      let target = res.data.PowerOffAfterTimeout.find((i: any)=>{
        return i.SystemId === item.id;
      });
      item.powerOffChecked = target.Enabled === 'On';
      showElMessage('success', traduction('COMMON_SUCCESS'));
      loading(false);
    })
    .catch(error => {
      item.powerOffChecked = !item.powerOffChecked;
      showElMessage('error', traduction('COMMON_FAILED'));
      loading(false);
    });
}

function offTimeRule(minNum, maxNum, item) {
  return {
    required: true,
    min: minNum ?? 10,
    max: maxNum ?? 6000,
    isInteger: true,
    trigger: 'change',
    validator: (vRule: any, valueParams: any, callback: any): boolean => {
      const { max, min, required } = vRule;
      let value = valueParams;
      // 为空校验 与 数字校验
      if (required && !value && value !== 0) {
        item.offTimePopoverSetting.type = 'complex';
        item.offTimePopoverSetting.popoverSlotSetting.data = traduction('VALIDTOR_INTER_INTGER_RANGE', [
          min, max,
        ]);
        callback(new Error());
        return false;
      }
      // 输入的要是数字字符串 或者 数字，前提是整数
      const reg = /(^[\-0-9][0-9]*)$/;
      if (!reg.test(value)) {
        item.offTimePopoverSetting.type = 'complex';
        item.offTimePopoverSetting.popoverSlotSetting.data = traduction('VALID_INTEGER_INFO');
        callback(new Error());
        return false;
      }
      if (typeof value === 'string') {
        value = Number(value);
      }
      if (value || value === 0) {
        // 最小值
        if ((min || min === 0) && value < min) {
          item.offTimePopoverSetting.type = 'complex';
          item.offTimePopoverSetting.popoverSlotSetting.data = traduction(
            'VALIDTOR_INTER_INTGER_RANGE',
            [min, max],
          );
          callback(new Error());
          return false;
        }
        // 最大值
        if ((max || max === 0) && value > max) {
          item.offTimePopoverSetting.type = 'complex';
          item.offTimePopoverSetting.popoverSlotSetting.data = traduction(
            'VALIDTOR_INTER_INTGER_RANGE',
            [min, max],
          );
          callback(new Error());
          return false;
        }
      }
      item.offTimePopoverSetting.type = 'ordinary';
      callback();
      return true;
    },
  };
}

const offTimePopoverSetting = reactive({
  // 是否有
  show: true,
  // popover的类型,是简单的字符串还是比较复杂的自定义内容（自定义的需要传组件）
  type: 'ordinary', // ordinary(简单的字符串)或者complex(复杂的自定义展示组件)
  // 自定义的popover展示组件配置
  popoverSlotSetting: {
    // 展示的组件
    component: shallowRef(SingleLineFailurePrompt),
    // 传给组件的数据
    data: traduction('VALIDTOR_INTER_INTGER_RANGE', [10, 6000]),
  },
  // popover的类名
  popperClass: 'no-wrap-popover',
  // 展示内容
  content: traduction('VALID_VALUE_POWER_OFF_RANGE_TIP', [10, 6000, 600]),
  // 展示位置
  placement: 'top',
  // popover触发方式
  trigger: 'focus',
});

const delayPopoverSetting = reactive({
  show: true,
  type: 'ordinary',
  popoverSlotSetting: {
    component: shallowRef(SingleLineFailurePrompt),
    data: traduction('VALIDTOR_INTER_INTGER_RANGE', [0, 120]),
  },
  popperClass: 'no-wrap-popover',
  content: traduction('VALID_DELAY_POLICY_TIP'),
  placement: 'top',
  trigger: 'focus',
});

const delayRule = {
  required: true,
  min: 0,
  max: 120,
  isInteger: false,
  trigger: 'change',
  validator: (vRule: any, valueParams: any, callback: any) => {
    let value = valueParams;
    const { max, min, required } = vRule;
    const reg = /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/;
    // 为空校验 与 数字校验
    const condition = required && !value && value !== 0;
    if (condition || !reg.test(String(value))) {
      delayPopoverSetting.type = 'complex';
      delayPopoverSetting.popoverSlotSetting.data = traduction('VALID_NUMBER_INFO');
      callback(new Error());
      return;
    }

    if (typeof value === 'string') {
      value = Number(value);
    }
    if (value || value === 0) {
      // 最大精度0.1
      const reg0 = /^((\d+)|(\d+\.\d))$/;
      if (!reg0.test(String(value)) || Object.is(value, -0)) {
        delayPopoverSetting.type = 'complex';
        delayPopoverSetting.popoverSlotSetting.data = traduction('VALID_OUT_DECIMAL_PPOINT');
        callback(new Error());
        return;
      }
      // 最小值
      if ((min || min === 0) && value < min) {
        delayPopoverSetting.type = 'complex';
        delayPopoverSetting.popoverSlotSetting.data = traduction('VALID_DELAY_POLICY_TIP', [
          0,
          120,
        ]);
        callback(new Error());
        return;
      }
      // 最大值
      if ((max || max === 0) && value > max) {
        delayPopoverSetting.type = 'complex';
        delayPopoverSetting.popoverSlotSetting.data = traduction('VALID_DELAY_POLICY_TIP', [
          0,
          120,
        ]);
        callback(new Error());
        return;
      }
    }
    delayPopoverSetting.type = 'ordinary';
    callback();
  },
};

const powerOnPolicyType = {
  alwaysPowerOn: 'AlwaysPowerOn',
  alwaysPowerOff: 'AlwaysPowerOff',
  lastState: 'LastState',
};

const leakageSwitchStateDialogRef = ref();

const leakageSwitchStateDialogConfig = reactive({
  title: traduction('COMMON_CONFIRM'),
  content: traduction('COMMON_ASK_OK'),
});

const powerState = computed(() => getStoreData('loct', 'powerState'));
watch(
  () => powerState.value,
  () => {
    init(false);
  },
);

// 漏液检测卡在位时生效 开关发生修改
function leakageSwitchStateChange() {
  if (leakage.switchState) {
    leakageSwitchStateDialogConfig.content = traduction('POWER_LEAKAGE_DIALOG_TIP');
  } else {
    leakageSwitchStateDialogConfig.content = traduction('COMMON_ASK_OK');
  }
  leakageSwitchStateDialogRef.value.show();
}

// 是否确认 漏液检测卡在位时生效 开关的修改
function leakageSwitchStateDialogClose(flag: boolean) {
  if (flag) {
    loading(true);
    const params = {
      LeakStrategy: leakage.switchState ? 'AutoPowerOff' : 'ManualPowerOff',
    };
    setPowerControl(params)
      .then(() => {
        loading(false);
        leakageSwitchStateDialogRef.value.hide();
        showElMessage('success', traduction('COMMON_SUCCESS'));
        init();
      })
      .catch(() => {
        loading(false);
        leakageSwitchStateDialogRef.value.hide();
        leakage.switchState = !leakage.switchState;
        showElMessage('error', traduction('COMMON_FAILED'));
      });
  } else {
    leakage.switchState = !leakage.switchState;
    leakageSwitchStateDialogRef.value.hide();
  }
}

function dataFactory1(data: any) {
  switchState.value = data.PanelPowerButtonEnabled === 'Off' ? true : false;
  leakageSupport.value = data.LeakDetectionSupport;
  leakage.switchState = data.LeakStrategy === 'AutoPowerOff';

  const powerOffAfterTimeout = data?.PowerOffAfterTimeout || [];

  if (powerOffAfterTimeout.length > 0) {
    tableData.splice(0);
    for (let i = 0; i < powerOffAfterTimeout.length; i++) {
      tableData.push({
        powerState: '',
        powerType: '',
      });
      tableData[i].id = powerOffAfterTimeout[i]?.SystemId ?? '-1';
      tableData[i].name = powerOffAfterTimeout[i]?.SystemId ? `System${powerOffAfterTimeout[i]?.SystemId}` : '--';
      tableData[i].safePowerOffTimoutSeconds = powerOffAfterTimeout[i]?.TimeoutSeconds;
      tableData[i].powerOffChecked = powerOffAfterTimeout[i]?.Enabled === 'On';
      tableData[i].offTimeRule = offTimeRule(
        powerOffAfterTimeout[i]?.MinSeconds,
        powerOffAfterTimeout[i]?.MaxSeconds,
        tableData[i],
      );
      let num = powerOffAfterTimeout[i]?.DefaultSeconds;

      if (!(num || num === 0)) {
        num = 600;
      }
      tableData[i].num = num;

      offTimePopoverSetting.content = traduction('VALID_VALUE_POWER_OFF_RANGE_TIP', [
        powerOffAfterTimeout[i]?.MinSeconds,
        powerOffAfterTimeout[i]?.MaxSeconds,
        num,
      ]);
      tableData[i].offTimePopoverSetting = deepClone(offTimePopoverSetting);
    }
  }
  const powerRestoreDelay = data?.PowerRestoreDelay;
  if (powerRestoreDelay) {
    powerOnDelayedSelected.value = powerRestoreDelay?.Mode;
    powerOnDelayed[1].editor.value = powerRestoreDelay?.Seconds;
    powerOnDelayed[2].editor.value = powerRestoreDelay?.Seconds;
    powerOnDelayed[3].editor.value = powerRestoreDelay?.Seconds;
    powerOnDelayed[1].editor.oldValue = powerRestoreDelay?.Seconds;
    powerOnDelayed[2].editor.oldValue = powerRestoreDelay?.Seconds;
    powerOnDelayed[3].editor.oldValue = powerRestoreDelay?.Seconds;
    oldSeconds = powerRestoreDelay?.Seconds;
  }
  const powerOnStrategy = data.PowerOnStrategy;
  if (powerOnStrategy === powerOnPolicyType.alwaysPowerOn) {
    powerOnPolicySelected.value = traduction('POWER_KEEP_ON');
  } else if (powerOnStrategy === powerOnPolicyType.alwaysPowerOff) {
    powerOnPolicySelected.value = traduction('POWER_KEEP_DOWN');
  } else if (powerOnStrategy === powerOnPolicyType.lastState) {
    powerOnPolicySelected.value = traduction('POWER_KEEP_CONSISTT');
  } else {}
  oldData.powerOnPolicySelected = powerOnPolicySelected.value;
  oldData.powerOnDelayedSelected = powerOnDelayedSelected.value;
}

function dataFactory2() {
  const multiState = getStoreData('loct', 'multiPowerState')|| [];
  if (!checkSame(multiState, deepClone(tableData))) {
    dialogRef.value?.hide();
  }
  if (multiState.length > 0 && deepClone(tableData).length > 0) {
    for (let i = 0; i < multiState.length; i++) {
      for (let j = 0; j < tableData.length; j++) {
        if (tableData[j].id === multiState[i].SystemId) {
          tableData[j].powerType = multiState[i].State === 'On' ? 'success' : 'info';
          tableData[j].powerState = multiState[i].State === 'On' ? 'POWER_ON' : 'POWER_OFF';
        }
      }
    }
  }

  virtualKeyLists.push({
    id: 'nmi',
    show: !isArm,
    className: 'nmi',
    information: 'NMI',
    helpTips: 'POWER_NMI_TIP',
  });
}

function checkSame(newValue: any, oldValue: any): boolean {
  let result = true;
  if (newValue.length !== oldValue.length) {
    result = false;
  }
  for (let i = 0; i < newValue.length; i++) {
    if (newValue[i].State === 'On' && oldValue[i].powerState !== 'POWER_ON') {
      result = false;
    }
    if (newValue[i].State === 'Off' && oldValue[i].powerState !== 'POWER_OFF') {
      result = false;
    }
  }
  return result;
}

function init(needLoading?: boolean) {
  if (needLoading !== false) {
    loading(true);
  }
  getPowerControl()
    .then(res => {
      loading(false);
      setStoreData('loct', 'multiPowerState', res.data.PowerState);

      // 定时器只修改上下电状态，不修改其他的展示项
      if (res && res.data && needLoading !== false) {
        dataFactory1(res.data);
      }
    })
    .then(() => {
      if (needLoading !== false) {
        loading(false);
      }
      dataFactory2();
    })
    .catch(() => {
      loading(false);
    });
}

const dialogRef = ref();

const powerOffTimeEdit = reactive({
  editor: () => {},
  cancel: () => {},
  confirm: (val: any, item:any) => {
    loading(true);
    const param = {
      PowerOffAfterTimeout: {
        TimeoutSeconds: parseInt(val, 10),
      },
      SystemId: item.id ? item.id : '',
    };
    setPowerControl(param)
      .then((response: any) => {
        showElMessage('success', traduction('COMMON_SUCCESS'));
        init();
      })
      .catch((error: any) => {
        loading(false);
        showElMessage('error', traduction('COMMON_FAILED'));
        init();
      });
  },
});

// 通电开机策略
const powerOnPolicy: Array<IPowerOnPolicy> = [
  {
    id: 'TurnOn',
    label: traduction('POWER_KEEP_ON'),
    disabled: false,
  },
  {
    id: 'StayOff',
    label: traduction('POWER_KEEP_DOWN'),
    disabled: false,
  },
  {
    id: 'RestorePreviousState',
    label: traduction('POWER_KEEP_CONSISTT'),
    disabled: false,
  },
];

function powerOnPolicyChange() {
  setBtnState();
}

// 延迟上电设置
const powerOnDelayed: any = reactive([
  {
    value: 'DefaultDelay',
    label: traduction('POWER_DEFAULT_DELAY'),
    disabled: false,
    desc: traduction('POWER_DEFAULT_DELAY_INFO1'),
    editor: {
      show: false,
    },
  },
  {
    value: 'HalfDelay',
    label: traduction('POWER_HALF_DELAY'),
    disabled: false,
    desc: traduction('POWER_HALF_DELAY_INFO'),
    editor: {
      show: true,
      value: '',
      oldValue: '',
      editor: () => {
        saveBtn.value = true;
      },
      cancel: () => {
        setBtnState(1);
      },
      confirm: (val: any) => {
        powerOnDelayed[1].editor.value = val;
        if (powerOnDelayed[1].editor.oldValue !== val) {
          saveBtn.value = false;
        } else {
          setBtnState();
        }
      },
    },
    delayRule: { ...delayRule },
  },
  {
    value: 'FixedDelay',
    label: traduction('POWER_FIXED_DELAY'),
    disabled: false,
    desc: traduction('POWER_FIXED_DELAY_INFO'),
    editor: {
      show: true,
      value: '',
      oldValue: '',
      editor: () => {
        saveBtn.value = true;
      },
      cancel: () => {
        setBtnState(2);
      },
      confirm: (val: any) => {
        powerOnDelayed[2].editor.value = val;
        if (powerOnDelayed[2].editor.oldValue !== val) {
          saveBtn.value = false;
        } else {
          setBtnState();
        }
      },
    },
    delayRule: { ...delayRule },
  },
  {
    value: 'RandomDelay',
    label: traduction('POWER_RANDOM_DELAY'),
    disabled: false,
    desc: traduction('POWER_RANDOM_DELAY_INFO'),
    editor: {
      show: true,
      value: '',
      oldValue: '',
      editor: () => {
        saveBtn.value = true;
      },
      cancel: () => {
        setBtnState(3);
      },
      confirm: (val: any) => {
        powerOnDelayed[3].editor.value = val;
        if (powerOnDelayed[3].editor.oldValue !== val) {
          saveBtn.value = false;
        } else {
          setBtnState();
        }
      },
    },
    delayRule: { ...delayRule },
  },
]);

const dialogConfig = reactive({
  value: '',
  id: '',
  content: traduction('COMMON_ASK_OK'),
  title: traduction('ALARM_OK'),
});
const powerControlParam = {
  OperateType: '',
};

// 虚拟按键二次确认弹框
function virtualKeyClick(val: any) {
  if (multipleSelection.value.length === 0) {
    dialogConfig.content = traduction('POWERONOFF_CHOOSE_LEAST');
  } else {
    switch (val) {
      case 'on':
        dialogConfig.content = traduction('COMMON_ASK_OK');
        powerControlParam.OperateType = 'On';
        dialogConfig.value = 'On';
        break;
      case 'off':
        dialogConfig.content = traduction('COMMON_ASK_OK');
        powerControlParam.OperateType = 'GracefulShutdown';
        dialogConfig.value = 'GracefulShutdown';
        break;
      case 'forcedOff':
        dialogConfig.content = traduction('POWER_STRONG_DOWN_POWER_TIP');
        powerControlParam.OperateType = 'ForceOff';
        dialogConfig.value = 'ForceOff';
        break;
      case 'forcedRestart':
        dialogConfig.content = traduction('POWER_REST_START_TIP');
        powerControlParam.OperateType = 'ForceRestart';
        dialogConfig.value = 'ForceRestart';
        break;
      case 'powerCycle':
        dialogConfig.content = traduction('POWER_SAFE_LABLE_TIP');
        powerControlParam.OperateType = 'PowerCycle';
        dialogConfig.value = 'PowerCycle';
        break;
      case 'forcedCycle':
        dialogConfig.content = traduction('POWER_OFF_POWER_ON_TIP');
        powerControlParam.OperateType = 'ForcePowerCycle';
        dialogConfig.value = 'ForcePowerCycle';
        break;
      case 'acCycle':
        dialogConfig.content = traduction('POWER_AC_LABLE_TIP');
        powerControlParam.OperateType = 'ACCycle';
        dialogConfig.value = 'ACCycle';
        break;
      case 'nmi':
        dialogConfig.content = traduction('POWER_NMI_LABEL_TIP');
        powerControlParam.OperateType = 'Nmi';
        dialogConfig.value = 'Nmi';
        break;
      default:
        break;
    }
    if (val === 'on') {
      dialogConfig.content += `<br/>${traduction('POWER_STRONG_ON_POWER_TIP')}`;
    } else if (val === 'forcedRestart') {
      dialogConfig.content += `<br/>${traduction('POWER_OTHER_OFF_ALERT_TIP')}<br/>${traduction(
        'POWER_STRONG_ON_POWER_TIP',
      )}`;
    } else if (['forcedCycle', 'powerCycle'].includes(val)) {
      dialogConfig.content += `<br/>${traduction('POWER_OTHER_OFF_ALERT_TIP')}<br/>${traduction(
        'POWER_STRONG_ON_POWER_TIP',
      )}`;
    } else {
      dialogConfig.content += `<br/>${traduction('POWER_OTHER_OFF_ALERT_TIP')}`;
    }
  }
  dialogRef.value.show();
}
// 关闭dialog
function dialogClose(reason: boolean) {
  dialogRef.value.hide();
  if (dialogConfig.content === traduction('POWERONOFF_CHOOSE_LEAST')) {
    return;
  }
  if (reason) {
    // 下电状态执行非上电操作
    let error = '';
    for (let obj of multipleSelection.value) {
      if (obj.powerState === 'POWER_OFF' && powerControlParam.OperateType !== 'On') {
        error += `${obj.name},`;
      } else {
        setPowerOnOff(powerControlParam, obj.id).then(res => {
          showElMessage('success', `${obj.name} ${traduction('COMMON_SUCCESS')}`);
        })
        .catch((err: any) => {
          showFWMessage(err);
        });
      }
    }
    if (error) {
      error = error.slice(0, error.length - 1);
      showElMessage('error', `${error} ${traduction('POWERONOFF_COMMAND')}`);
    }
    multipleTable.value.clearSelection();
  }
}
// 漏液自动下电
const leakage = reactive({
  switchState: false,
});

// 延迟上电设置的radio发生修改
function delayRadioChange(val: any, key?: number) {
  setBtnState(key);
}

// 设置保存按钮的状态
function setBtnState(key?: number) {
  const obj = {
    powerOnPolicySelected: powerOnPolicySelected.value,
    powerOnDelayedSelected: powerOnDelayedSelected.value,
  };
  let diff = false;
  if (key && powerOnDelayed[key].editor.value !== powerOnDelayed[key].editor.oldValue) {
    diff = true;
  }
  saveBtn.value = !diff && compareObjectEqual(obj, oldData);
}

// 获取请求参数
function getParams() {
  let param: any = {};
  if (powerOnPolicySelected.value !== oldData.powerOnPolicySelected) {
    if (powerOnPolicySelected.value === traduction('POWER_KEEP_ON')) {
      param.PowerOnStrategy = powerOnPolicyType.alwaysPowerOn;
    } else if (powerOnPolicySelected.value === traduction('POWER_KEEP_DOWN')) {
      param.PowerOnStrategy = powerOnPolicyType.alwaysPowerOff;
    } else if (powerOnPolicySelected.value === traduction('POWER_KEEP_CONSISTT')) {
      param.PowerOnStrategy = powerOnPolicyType.lastState;
    } else {}
  }
  if (powerOnDelayedSelected.value !== oldData.powerOnDelayedSelected) {
    param.PowerRestoreDelay = {
      Mode: powerOnDelayedSelected.value,
    };
  }
  switch (powerOnDelayedSelected.value) {
    case 'HalfDelay':
      param = setSeconds(1, param);
      break;
    case 'FixedDelay':
      param = setSeconds(2, param);
      break;
    case 'RandomDelay':
      param = setSeconds(3, param);
      break;
    default:
      break;
  }
  return param;
}
function setSeconds(val: number, param: any) {
  if (powerOnDelayed[val].editor.value !== oldSeconds) {
    if (param.PowerRestoreDelay) {
      param.PowerRestoreDelay['Seconds'] = parseFloat(powerOnDelayed[val].editor.value);
    } else {
      param.PowerRestoreDelay = {
        Seconds: parseFloat(powerOnDelayed[val].editor.value),
      };
    }
  }
  return param;
}

function handleSelectionChange(val: any) {
  multipleSelection.value = val;
}

// 点击保存按钮
function save() {
  loading(true);
  setPowerControl(getParams())
    .then(() => {
      loading(false);
      showElMessage('success', traduction('COMMON_SUCCESS'));
      saveBtn.value = true;
      init();
    })
    .catch(() => {
      loading(false);
      saveBtn.value = true;
      init();
    });
}

function canSelect(row) {
  return isPrivileges;
}

onMounted(() => {
  init();
  getStateTimer = setInterval(() => {
    init(false);
  }, 10000);
});

onUnmounted(() => {
  if (getStateTimer) {
    clearInterval(getStateTimer);
  }
});
</script>

<template>
  <div class="page-top">
    <!-- 虚拟按钮 -->
    <div class="power-virtual-keys">
      <!-- 虚拟按键列表 -->
      <div class="button-list">
        <template v-for="item in virtualKeyLists" :key="item.id">
          <div v-if="item.show" :class="['list-item', item.className]">
            <el-tooltip
              :content="$t(item.helpTips || '')"
              trigger-keys
              :disabled="!item.helpTips"
              placement="top"
              :class="`${item.id}Top`"
            >
              <el-button :id="item.id" :disabled="!isPrivileges" @click="virtualKeyClick(item.id)">
                {{ $t(item.information) }}
              </el-button>
            </el-tooltip>
          </div>
        </template>
      </div>
      <div id="powerList">
        <el-table
          ref="multipleTable"
          v-addId.table="'multiPowerTable'"
          :data="tableData"
          border
          resizable
          @selection-change="handleSelectionChange"
        >
          <el-table-column min-width="5%" type="selection" :selectable="canSelect" />
          <el-table-column min-width="40%" :label="$t('POWER_NAME')">
            <template #default="scope">
              <span :id="scope.row.name" class="powerId">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="30%" :label="$t('FDM_POWER_STATUS')">
            <template #default="scope">
              <div :id="`powerState${scope.row.id}`" class="system-state">
                <el-tag :type="scope.row.powerType">{{ $t(scope.row.powerState) }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="30%" :label="$t('POWER_OPERATION')">
            <template #default="scope">
              <div :id="`powerEditor${scope.row.id}`" class="powerEditor">
                <el-checkbox
                  v-model="scope.row.powerOffChecked"
                  v-addId.select="`powerOffTime${scope.row.id}`"
                  :disabled="!isPrivileges || isSystemLock"
                  @change="powerOffTimeChange($event, scope.row)"
                >
                  {{ $t('POWER_OFF_TIME') }}
                </el-checkbox>
                <Editor
                  v-if="scope.row.powerOffChecked && isPrivileges && !isSystemLock"
                  :id-str="`powerOffEditor${scope.row.id}`"
                  :input-style="{ width: '56px' }"
                  :input-type="'text'"
                  :value="scope.row.safePowerOffTimoutSeconds"
                  :rule="scope.row.offTimeRule"
                  :popover-setting="scope.row.offTimePopoverSetting"
                  teleported="true"
                  @editor="powerOffTimeEdit.editor"
                  @cancel="powerOffTimeEdit.cancel"
                  @confirm="powerOffTimeEdit.confirm($event, scope.row)"
                />
              </div>
            </template>
          </el-table-column>
          <template #empty>
            <TableNoData />
          </template>
        </el-table>
      </div>
      <Dialog ref="dialogRef" :config="dialogConfig" @close="dialogClose">
        <template #default>
          <div class="content-item">
            <el-icon :size="24">
              <IconAlarm />
            </el-icon>
          </div>
          <div class="content-item text">
            <div v-html="dialogConfig.content"></div>
          </div>
        </template>
      </Dialog>
    </div>
  </div>
  <div class="page-buttom">
    <!-- 通电开机策略 -->
    <div id="powerOnPolicy" class="power-on-policy">
      <div class="title">{{ $t('POWER_POLICY') }}</div>
      <el-radio-group
        v-model="powerOnPolicySelected"
        :disabled="!isPrivileges || isSystemLock"
        @change="powerOnPolicyChange"
      >
        <el-radio-button
          v-for="item in powerOnPolicy"
          :id="item.id"
          :key="item.label"
          v-addTooltip.elRadioButton="200"
          :label="item.label"
          :disabled="item.disabled || isSystemLock"
        ></el-radio-button>
      </el-radio-group>
    </div>
    <!-- 延迟上电设置 -->
    <div class="power-on-delayed">
      <div class="title">{{ $t('POWER_DELAY_CONFIG') }}</div>
      <el-radio-group
        v-model="powerOnDelayedSelected"
        class="delayed-content"
        :disabled="!isPrivileges || isSystemLock"
      >
        <el-radio
          v-for="(item, index) in powerOnDelayed"
          :key="item.label"
          v-addId.radio="item.value"
          :label="item.value"
          @change="delayRadioChange($event, index)"
        >
          <div class="radio-content">
            <span>{{ item.label }}</span>
            <span class="desc-info">{{ item.desc }}</span>
            <Editor
              v-if="
                item.editor.show &&
                  powerOnDelayedSelected === item.value &&
                  isPrivileges &&
                  !isSystemLock
              "
              :id-str="'powerOnDelayedEditor'"
              :input-style="{ width: '56px' }"
              :input-type="'text'"
              :value="item.editor.value"
              :rule="item.delayRule"
              :popover-setting="delayPopoverSetting"
              @editor="item.editor.editor"
              @cancel="item.editor.cancel"
              @confirm="item.editor.confirm"
            />
            <span
              v-if="
                item.editor.show &&
                  (powerOnDelayedSelected !== item.value || !isPrivileges || isSystemLock)
              "
              class="info"
            >
              --
            </span>
          </div>
        </el-radio>
      </el-radio-group>
    </div>
    <el-button
      v-if="isPrivileges"
      id="powerContorlSaveId"
      :disabled="saveBtn || isSystemLock"
      type="primary"
      @click="save"
    >
      {{ $t('COMMON_SAVE') }}
    </el-button>
    <!-- 漏液自动下电 -->
    <div v-if="leakageSupport" class="leakage">
      <div class="title leakage-title">{{ $t('POWER_LEAKAGE_POWEROFF') }}</div>
      <div class="leakage-content">
        <el-switch
          id="leakage"
          v-model="leakage.switchState"
          :disabled="!isPrivileges || isSystemLock"
          @change="leakageSwitchStateChange"
        ></el-switch>
        <span>{{ $t('POWER_LEAKAGE_TIP') }}</span>
      </div>
    </div>

    <Dialog
      ref="leakageSwitchStateDialogRef"
      :config="leakageSwitchStateDialogConfig"
      @close="leakageSwitchStateDialogClose"
    ></Dialog>
  </div>
</template>

<style lang="scss" scoped>
.page-top,
.page-buttom {
  background-color: var(--o-bg-color-base);
  border-radius: 4px;
  padding: 24px;
  margin-bottom: 16px;
  margin-right: 24px;
  .title {
    font-size: 16px;
    font-weight: 600;
    color: var(--o-text-color-primary);
    line-height: 24px;
    margin-bottom: 16px;
  }
  .el-icon {
    color: var(--o-text-color-tertiary);
    &:hover {
      color: var(--o-color-primary-secondary);
      cursor: pointer;
    }
  }
}
.system-state {
  .el-tag {
    height: 16px;
    width: 64px;
    padding: 0;
    font-weight: 600;
  }
}
.power-virtual-keys {
  .button-list {
    display: flex;
    justify-content: flex-end;
    .list-item {
      margin-bottom: 16px;
      height: 32px;
      line-height: 32px;
      display: flex;
      align-items: center;
      &:nth-last-child(1) {
        margin-bottom: 0;
      }
      .editor-icon {
        vertical-align: middle;
        margin-left: 8px;
        &:hover {
          cursor: pointer;
        }
      }
      .el-checkbox {
        margin-right: 16px;
      }
      .seconds {
        color: var(--o-text-color-secondary);
        line-height: 16px;
      }
      :deep(.el-button){
        span{
          max-width: 100px;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
    .el-button {
      height: 32px;
      margin-right: 8px;
    }
    .item-info {
      color: var(--o-text-color-tertiary);
      line-height: 16px;
      vertical-align: middle;
    }
    .power-off {
      :deep(.el-input) {
        width: 36px;
        .el-input__inner {
          padding-left: 0 !important;
          text-align: center;
        }
      }
    }
  }
  .powerEditor {
    display: flex;
    #powerOffTime {
      margin-right: 16px;
    }
  }
}
.panel-btn {
  margin-bottom: 24px;

  .panel-btn-content {
    display: flex;
    align-items: center;
  }

  span {
    color: var(--o-text-color-secondary);
    line-height: 16px;
    margin-right: 4px;
  }
}
.wake-on-lan {
  margin-bottom: 24px;
  .wake-label {
    margin-right: 24px;
  }
}
.power-on-policy {
  margin-bottom: 24px;

  :deep(.el-radio-group .el-radio-button) {
    margin-bottom: 0 !important;
  }
}
.power-on-delayed {
  margin-bottom: 16px;
}
.leakage {
  margin-top: 24px;

  .leakage-content {
    display: flex;
    align-items: center;
  }

  .el-switch {
    margin-right: 24px;
  }
}
.no-margin {
  margin-top: 0px;
}
.substitute {
  width: 16px;
  height: 16px;
  margin-right: 16px;
}
.panel-tip {
  margin-right: 24px;
}
.delayed-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  :deep(.el-radio__label) {
    display: flex;
    align-items: center;
  }

  :deep(.radio-content) {
    display: flex;
    align-items: center;

    .desc-info {
      margin-left: 8px;
      color: var(--o-text-color-tertiary);
    }
    .editor-box .btn-box .value span {
      font-size: 12px;
      color: #8d98aa;
      letter-spacing: 0;
      line-height: 16px;
    }
  }

  :deep(.el-radio) {
    margin-bottom: 8px;

    &:nth-last-child(1) {
      margin-bottom: 0;
    }
  }
}
.list-item {
  display: flex;
}

#powerList{
  :deep(.el-checkbox .is-indeterminate .el-checkbox__inner)::before {
    left: 3px;
    top: 3px;
  }
  :deep(th.el-table__cell):nth-child(1){ 
    .cell {
      border-right: none;
    }
  }
}

.content-item.text {
  margin-left: 16px;
  padding-top: 4px;
}
</style>
